package web.demo.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import web.demo.entity.Food;
import web.demo.entity.FoodDetail;
import web.demo.entity.FoodTable;
import web.demo.entity.FoodType;
import web.demo.entity.Orders;
import web.demo.factory.BeanFactory;
import web.demo.service.impl.FoodService;
import web.demo.service.impl.FoodTableService;
import web.demo.service.impl.FoodTypeService;
import web.demo.utils.Condition;
import web.demo.utils.PageBean;
import web.demo.utils.WebUtils;

public class FoodServlet extends BaseServlet {
	
	protected Object test(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		return null;
	}
	//菜品列表（前台）
	protected Object foodList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session=request.getSession();
		//获取餐桌id
		int foodTableId=0;
		Orders orders;
		//是否清除订单详情集合
		boolean clearOrderDetail=true;
		if(request.getParameter("foodTableId")!=null){
			foodTableId=Integer.parseInt(request.getParameter("foodTableId"));
			//获取餐桌信息
			FoodTable foodTable=foodTableService.getById(foodTableId);
			//放入session中，用来生成订单
			session.setAttribute("foodTable",foodTable);
			//创建订单
			if(session.getAttribute("orders")!=null){
				orders=(Orders) session.getAttribute("orders");
				if(orders.getFoodTable_id()==foodTableId){
					clearOrderDetail=false;
				}else{
					clearOrderDetail=true;
				}
			}
			if(clearOrderDetail){
				orders=new Orders();
				orders.setFoodTable_id(foodTableId);
				orders.setId(foodTableId);
				orders.setFoodTable_name(foodTable.getName());
				//将订单放入session中
				session.setAttribute("orders",orders);
			}
			session.setAttribute("clearOrderDetail",clearOrderDetail);
		}
		//设置跳转对象
		Object uri=null;
		//查询条件
		PageBean pageBean=new PageBean();
		Condition condition=new Condition();
		//获取查询的菜系id和菜品名称
		int foodTypeId=-1;
		String foodName=null;
		if(request.getParameter("foodTypeId")!=null){
			foodTypeId=Integer.parseInt(request.getParameter("foodTypeId"));
		}
		if(request.getParameter("foodName")!=null){
			foodName=new String(request.getParameter("foodName").getBytes("ISO-8859-1"),"utf-8");
		}
		if(foodTypeId>0){
			//若foodTypeId>0则表示是按照菜系查询
			condition.setFoodTypeId(foodTypeId);
		}
		if(foodName!=null && !"".equals(foodName.trim())){
			//按照菜品名称查询
			condition.setFoodName(foodName);
		}
		if(condition!=null){
			pageBean.setCondition(condition);
		}
		
		//得到所有的行数
		int totalRows=foodService.getFoodCount(pageBean);
		pageBean.setTotalRows(totalRows);
		//得到总的页数
		int totalPages=pageBean.getTotalPages();
		//获取当前页数
		int currentPage=-1;
		if(request.getParameter("currentPage")!=null){
			currentPage=Integer.parseInt(request.getParameter("currentPage"));
		}
		if(currentPage<1){
			currentPage=1;
		}
		if(currentPage>totalPages && totalPages>0){
			currentPage=totalPages;
		}
		pageBean.setCurrentPage(currentPage);
		//分页获取菜品列表和菜系列表
		List<Food> foodList=foodService.getFoodAll(pageBean);
		
		//获取所有的菜系
		List<FoodType> foodTypeList=foodTypeService.getAll();
		
		//将菜品列表，分页对象发送到主界面
		request.setAttribute("foodName",foodName);
		request.setAttribute("foodTypeId",foodTypeId);
		request.setAttribute("foodList",foodList);
		request.setAttribute("pageBean",pageBean);
		session.setAttribute("foodTypeList",foodTypeList);
		
		//跳转
		uri=request.getRequestDispatcher("app/detail/caidan.jsp");
		return uri;
	}
	//菜品详情（前台）
	protected Object foodDetail(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Object uri=null;
		int foodId=Integer.parseInt(request.getParameter("foodId"));
		Food food=foodService.getFoodById(foodId);
		request.setAttribute("food",food);
		uri=request.getRequestDispatcher("app/detail/foodDetail.jsp");
		return uri;
	}
	//菜品详情列表（后台）
	protected Object foodDetailList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//不需要分页
		List<FoodDetail> foodDetailList=foodDetailService.getAll();
		request.setAttribute("foodDetailList",foodDetailList);
		List<FoodType> foodTypeList=foodTypeService.getAll();
		HttpSession session=request.getSession();
		session.setAttribute("foodTypeList",foodTypeList);
		
		return request.getRequestDispatcher("sys/food/foodList.jsp");
	}
	//显示菜系（后台）
	protected Object foodTypeList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<FoodType> foodTypeList=foodTypeService.getAll();
		request.setAttribute("foodTypeList",foodTypeList);
		
		return request.getRequestDispatcher("sys/food/saveFood.jsp");
	}
	//添加菜品（后台）	
	protected Object addFood(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Food food=new Food();
		//接收并处理参数
		//返回图片路径
		int foodTypeId=0;
		String foodName=null;
		double vipPrice=0;
		double price=0;
		String description=null;
		FileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload upload=new ServletFileUpload(factory);
		upload.setFileSizeMax(2*1024*1024);
		upload.setSizeMax(100*1024*1024);
		upload.setHeaderEncoding("utf-8");
		if(upload.isMultipartContent(request)){
			try {
				List<FileItem> list=upload.parseRequest(request);
				for(FileItem fileItem:list){
					if(fileItem.isFormField()){
						//文本数据
						String value=fileItem.getString();
						String itemName=fileItem.getFieldName();
						if("foodTypeId".equals(itemName)){
							foodTypeId=Integer.parseInt(value);
						}
						if("foodName".equals(itemName)){
							foodName=new String(value.getBytes("ISO-8859-1"),"utf-8");
						}
						if("price".equals(itemName)){
							price=Double.parseDouble(value);
						}
						if("vipPrice".equals(itemName)){
							vipPrice=Double.parseDouble(value);
						}
						if("description".equals(itemName)){
							if(value != null ){
								description=new String(value.getBytes("ISO-8859-1"),"utf-8");
							}else{
								description="";
							}
						}
					}else{
						//文件数据
						String name=fileItem.getName();
						
						String id=UUID.randomUUID().toString().replace("-","");
						//String tempName=id+name.substring(name.lastIndexOf("."));
						String urlFoodName=URLEncoder.encode(foodName, "utf-8").replace("%","");
						String tempName=id+"foodImg"+urlFoodName+name.substring(name.lastIndexOf("."));
						//获取上传路径
						String path=request.getServletContext().getRealPath("app/detail/style/images");
						//String path=this.getClass().getResource("/WebRoot/app/detail/style/images").getPath(); 
						///E:/javaWeb/Hotel_version_1/WebRoot/WEB-INF/classes/web/demo/test/
						//String path="E:/javaWeb/Hotel_version_1/WebRoot/app/detail/style/images";

						//封装
						food.setFoodType_id(foodTypeId);
						food.setName(foodName);
						food.setPrice(price);
						food.setVip_price(vipPrice);
						food.setDescription(description);
						food.setImg(tempName);
						System.out.println(food);
						boolean result=foodService.addFood(food);

						if(result){
							InputStream in=fileItem.getInputStream();
							File file=new File(path,tempName);
							File sysFile=new File(request.getServletContext().getRealPath("sys/style/images"),tempName);
							int len=-1;
							byte[] buf=new byte[1024];
							//FileOutputStream out=new FileOutputStream(file);
							FileOutputStream sysOut=new FileOutputStream(sysFile);
							while((len=in.read(buf)) != -1){
								//out.write(buf,0,len);	//可以直接这样写入两个输出流中
								sysOut.write(buf,0,len);
							}
							//fileItem.write(sysFile);
							fileItem.write(file);
							//out.close();
							sysOut.close();
							in.close();
							fileItem.delete();	//删除系统临时文件
							return request.getRequestDispatcher("FoodServlet?method=foodDetailList");
						}else{
							return "error/error.jsp";
						}
					}
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return "error!";
	}
	//获得指定菜品到更新界面（后台）
	protected Object getFoodById(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int foodId=Integer.parseInt(request.getParameter("foodId"));
		Food food=foodService.getFoodById(foodId);
		request.setAttribute("foodUpdate",food);
		
		return request.getRequestDispatcher("sys/food/updateFood.jsp"); 
	}
	//更新菜品（后台）
	protected Object updateFood(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Food food=new Food();
		//接收并处理参数
		//返回图片路径
		int foodId=0;
		int foodTypeId=0;
		String foodName=null;
		double vipPrice=0;
		double price=0;
		String description=null;
		String img=null;
		FileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload upload=new ServletFileUpload(factory);
		upload.setFileSizeMax(2*1024*1024);
		upload.setSizeMax(100*1024*1024);
		upload.setHeaderEncoding("utf-8");
		if(upload.isMultipartContent(request)){
			try {
				List<FileItem> list=upload.parseRequest(request);
				for(FileItem fileItem:list){
					if(fileItem.isFormField()){
						//文本数据
						String value=fileItem.getString();
						String itemName=fileItem.getFieldName();
						if("foodId".equals(itemName)){
							foodId=Integer.parseInt(value);
						}
						if("foodTypeId".equals(itemName)){
							foodTypeId=Integer.parseInt(value);
						}
						if("foodName".equals(itemName)){
							foodName=new String(value.getBytes("ISO-8859-1"),"utf-8");
						}
						if("price".equals(itemName)){
							price=Double.parseDouble(value);
						}
						if("vipPrice".equals(itemName)){
							vipPrice=Double.parseDouble(value);
						}
						if("description".equals(itemName)){
							if(value != null ){
								description=new String(value.getBytes("ISO-8859-1"),"utf-8");
							}else{
								description="";
							}
						}
						if("imgUrl".equals(itemName)){
							img=value;
						}
					}else{
						//文件数据
						String fileName=fileItem.getName();
						//获取上传路径
						String path=request.getServletContext().getRealPath("app/detail/style/images");
						String sysPath=request.getServletContext().getRealPath("sys/style/images");
						//封装
						food.setId(foodId);
						food.setFoodType_id(foodTypeId);
						food.setName(foodName);
						food.setPrice(price);
						food.setVip_price(vipPrice);
						food.setDescription(description);
						
						String id=null;
						String tempName=null;
						if(fileName!=null && !"".equals(fileName)){	//上传图片
							//拼接新图片的名字，并添加到数据库img中
							id=UUID.randomUUID().toString().replace("-","");
							tempName=id+fileName.substring(fileName.lastIndexOf("."));
							food.setImg(tempName);
							//拼装完毕，执行更新
							foodService.update(food);
							//若原图存在，则删除
							File oldFile=new File(path,img);
							File oldSysFile=new File(sysPath,img);
							if(oldFile.exists()){
								oldFile.delete();
							}
							if(oldSysFile.exists()){
								oldSysFile.delete();
							}
							//将更新的图片添加到指定文件夹中
							File file=new File(path,tempName);
							File sysFile=new File(sysPath,tempName);
							InputStream in=fileItem.getInputStream();
							FileOutputStream out=new FileOutputStream(sysFile);
							byte[] buf=new byte[1024];
							int len=-1;
							while((len=in.read(buf)) !=-1 ){
								out.write(buf,0,len);
							}
							out.close();
							in.close();
							fileItem.write(file);
							fileItem.delete();	//删除系统临时文件
						}else{	//没有上传图片
							//图片img地址仍然是原来的地址
							food.setImg(img);
							//拼装完毕，执行更新
							foodService.update(food);;
						}
						
						return request.getRequestDispatcher("FoodServlet?method=foodDetailList");
					}
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return "error!";
	}
	//根据名称或id搜索食品（后台）
	protected Object search(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String selectCondition="";
		if(request.getParameter("selectCondition")!=null){
			selectCondition=new String(request.getParameter("selectCondition").trim().getBytes("ISO-8859-1"),"utf-8");
		}
		List<FoodDetail> foodDetailList=foodDetailService.search(selectCondition);
		request.setAttribute("foodDetailList",foodDetailList);
		
		return request.getRequestDispatcher("sys/food/foodList.jsp");
	}
	//删除菜品
	protected Object delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int foodId=Integer.parseInt(request.getParameter("foodId"));
		String appPath=request.getServletContext().getRealPath("app/detail/style/images/");
		String sysPath=request.getServletContext().getRealPath("sys/style/images/");
		foodService.delete(foodId,appPath,sysPath);
		
		return request.getRequestDispatcher("FoodServlet?method=foodDetailList");
	}
}
